<?php
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
	/** * oauth版本 2.0*/
// +----------------------------------------------------------------------

abstract class BaseOauth{

	/** * 申请应用时分配的app_key */
	protected $AppKey = '';

	/** * 申请应用时分配的 app_secret */
	protected $AppSecret = '';

	/** * 回调页面URL  可以通过配置文件配置 */
	protected $Callback = '';

	/** * 获取request_code的额外参数 URL查询字符串格式 */
	protected $Authorize = '';

	/** * 获取request_code请求的URL */
	protected $GetRequestCodeURL = '';

	/** * 获取access_token请求的URL */
	protected $GetAccessTokenURL = '';

	/** * API根路径 */
	protected $ApiBase = '';

	/** * 授权后获取到的TOKEN信息 */
	protected $Token = null;

	/** * 构造方法，配置应用信息 */
	public function __construct($token = null){
		//设置SDK类型
		$class = get_class($this);
		$type = strtoupper($class);

		//获取应用配置
		$config = C("OAUTH_{$type}");
		if(!($config['CALLBACK'])) 	 throw new Exception('请配置回调页面地址');
		if(!$config['APP_KEY']) 	 throw new Exception('请配置您申请的APP_KEY');
		if(!$config['APP_SECRET'])   throw new Exception('请配置您申请的APP_SECRET');

		$this->AppKey    = $config['APP_KEY'];
		$this->AppSecret = $config['APP_SECRET'];
		$this->Callback = $config['CALLBACK'];

		($config['AUTHORIZE']) && $this->Authorize = $config['AUTHORIZE'];
		$this->Token     = $token; //设置获取到的TOKEN			
	}

	/**
     * 取得Oauth实例
     * @static
     * @return mixed 返回Oauth
     */
    public static function getInstance($type, $token = null) {
    	$name = (strtolower($type));
    	require_once "{$name}.class.php";
    	if (class_exists($name)) {
    		return new $name($token);
    	} else {
    		halt(L('_CLASS_NOT_EXIST_') . ':' . $name);
    	}
    }

	/**
	 * 请求code
	 */
	public function getRequestCode($param = array()){
		//Oauth 标准参数
		$params = array(
			'client_id'     => $this->AppKey,
			'redirect_uri'  => urlencode($this->Callback),
			'response_type' => 'code',
		);
		$params = array_merge($params, $param);

		//获取额外参数
		if($this->Authorize){
			parse_str($this->Authorize, $_param);
			if(is_array($_param)){
				$params = array_merge($params, $_param);
			} else {
				throw new Exception('AUTHORIZE配置不正确！');
			}
		}
		_redirect( $this->GetRequestCodeURL . '?' . http_build_query($params) );
	}

	/**
	 * 获取access_token
	 * @param string $code 上一步请求到的code
	 */
	public function getAccessToken($code, $extend = null){
		$params = array(
				'client_id'     => $this->AppKey,
				'client_secret' => $this->AppSecret,
				'grant_type'    => 'authorization_code',
				'code'          => $code,
				'redirect_uri'  => $this->Callback,
		);

		$data = $this->http($this->GetAccessTokenURL, $params, 'POST');
		$this->Token = $this->parseToken($data, $extend);
		return $this->Token;
	}

	protected function param($params, $param){
		if(is_string($param))
			parse_str($param, $param);
		return array_merge($params, $param);
	}

	protected function url($api, $fix = ''){
		return $this->ApiBase . $api . $fix;
	}

	/**
	 * 发送HTTP请求方法，目前只支持CURL发送请求
	 * @param  string $url    请求URL
	 * @param  array  $params 请求参数
	 * @param  string $method 请求方法GET/POST
	 * @return array  $data   响应数据
	 */
	protected function http($url, $params, $method = 'GET', $header = array(), $multi = false){
		$opts = array(
			CURLOPT_TIMEOUT        => 30,
			CURLOPT_RETURNTRANSFER => 1,
			CURLOPT_SSL_VERIFYPEER => false,
			CURLOPT_SSL_VERIFYHOST => false,
			CURLOPT_HTTPHEADER     => $header
		);

		/* 根据请求类型设置特定参数 */
		switch(strtoupper($method)){
			case 'GET':
				$opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
				break;
			case 'POST':
				//判断是否传输文件
				$params = $multi ? $params : http_build_query($params);
				$opts[CURLOPT_URL] = $url;
				$opts[CURLOPT_POST] = 1;
				$opts[CURLOPT_POSTFIELDS] = $params;
				break;
			default:
				throw new Exception('不支持的请求方式！');
		}

		/* 初始化并执行curl请求 */
		$ch = curl_init();
		curl_setopt_array($ch, $opts);
		$data  = curl_exec($ch);
		$error = curl_error($ch);
		curl_close($ch);
		if($error) throw new Exception('请求发生错误：' . $error);
		return  $data;
	}

	abstract protected function call($api, $param = '', $method = 'GET', $multi = false);
	abstract protected function parseToken($result, $extend);
	abstract public function openid();
	abstract public function getuserinfo($token);
}
